package com.hk.commons.domain.service;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * Created by Antinomy on 16/12/14.
 */
@Service
public class UploadService {

    private Logger logger = LoggerFactory.getLogger(UploadService.class);

    private String ACCESS_KEY;
    private String SECRET_KEY;

    private Auth auth;
    private Zone zone;
    private Configuration config;

    public UploadService(@Value("${qiniu.ACCESS_KEY}") String access_key, @Value("${qiniu.SECRET_KEY}") String secret_key) {
        this.ACCESS_KEY = access_key;
        this.SECRET_KEY = secret_key;

        //密钥配置
        auth = Auth.create(ACCESS_KEY, SECRET_KEY);

        //要上传的空间(bucket)的存储区域为华南时
        zone = Zone.zone2();
        config = new Configuration(zone);
    }


    public String uploadFile(String bucket, String uploadedFileName, byte[] fileBytes) {
        String result = null;

        //创建上传对象
        UploadManager uploadManager = new UploadManager(config);

        try {
            //调用put方法上传
            String upToken = this.getUpToken(bucket);
            Response res = uploadManager.put(fileBytes, uploadedFileName, upToken);

            result = res.bodyString();

            //打印返回的信息
            logger.info(result);

        } catch (QiniuException e) {
            Response res = e.response;

            // 请求失败时打印的异常的信息
            if (res != null) {
                logger.error(res.toString());

                try {
                    //响应的文本信息
                    result = res.bodyString();
                    logger.error(result);
                } catch (QiniuException e1) {
                    //ignore
                }
            } else {
                logger.error(e.getMessage());
                result = e.getMessage();
            }
        }

        return result;
    }

    public String getUpToken(String bucketname) {
        return auth.uploadToken(bucketname);
    }

}
